package com.zhiyou100.crm.dao.impl;

import com.zhiyou100.crm.dao.MessageDao;
import com.zhiyou100.crm.util.DBUtil1;
import com.zhiyou100.crm.util.Message;
import com.zhiyou100.crm.util.Role;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class MesageDaoImpl implements MessageDao {
    DBUtil1 dbUtil1 = new DBUtil1();
    ResultSet rs = null;
    ;
    @Override
    public List<Message> queryMessage() {
        List<Message> messages= new ArrayList<>();
        String sql = "select a.*,b.username from message as a,user as b where a.receiver=b.user_id";
        rs = dbUtil1.select(sql, null);
        try {
            while (rs.next()) {
                int message_id = rs.getInt("message_id");
                int sender = rs.getInt("sender");
                String subject = rs.getString("subject");
                String content = rs.getString("content");
                Timestamp save_time = rs.getTimestamp("save_time");
                Timestamp send_time = rs.getTimestamp("send_time");
                Timestamp send_update_time = rs.getTimestamp("send_update_time");
                Timestamp receive_update_time = rs.getTimestamp("receive_update_time");
                int send_delete = rs.getInt("send_delete");
                int send_status = rs.getInt("send_status");
                int receiver = rs.getInt("receiver");
                int receive_delete = rs.getInt("receive_delete");
                int receive_status = rs.getInt("receive_status");
                String username = rs.getString("username");
                Message message=new Message(message_id,subject,content,sender,save_time,send_time,send_delete,send_status,send_update_time,receiver,receive_delete,receive_status,receive_update_time,username);
                messages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }finally {
            dbUtil1.close();
        }
        return messages;
    }


    @Override
    public int delete(int id) {
        String sql="delete from message where message_id=?";
        Object[] obj={id};
        return dbUtil1.update(sql,obj);
    }

    @Override
    public int update(Message message) {
        return 0;
    }

    @Override
    public int insert(Message message) {
        String sql="insert into message(receiver,subject,content,send_time,send_status) values(?,?,?,?,1)";
        Object[] obj={message.getReceiver(),message.getSubject(),message.getContent(),message.getSend_time()};
        return dbUtil1.update(sql,obj);
    }

    @Override
    public int insert1(Message message) {
        String sql="insert into message(receiver,subject,content,save_time,send_status) values(?,?,?,?,0)";
        Object[] obj={message.getReceiver(),message.getSubject(),message.getContent(),message.getSave_time()};
        return dbUtil1.update(sql,obj);
    }
}
